#!/usr/bin/python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""BabaOvo Application: Retweets Twitter Analyser Tool """

__author__ = 'caraciol@gmail.com'
__version__ = '0.2'



import twitterT
import operator

babaovo_username = 'username'
babaovo_password = 'password'

A_pos = 1

def babaovoByPages(user,all=False,count=200):
	api = twitterT.Api(babaovo_username,babaovo_password)
	
	statusFlag = True
	page=1
	babaovo = {}
	total = 0
	while statusFlag:
		print "Loading page..." + str(page)
		statusList = api.GetUserTimeline(user,count=count,page=page)
		if len(statusList) > 0:
			total += len(statusList)
			for st in statusList:
				status = st.GetText()
				if status.startswith('RT'):
					try:
						babaovo[rt(status)] = babaovo[rt(status)] + 1
					except:
						babaovo[rt(status)] = 1
			page+=1
		else:
			statusFlag = False
		
	print str(total) + "status read."
		
	if all:
		babaovo = babaovo.items()
		babaovo.sort(key=operator.itemgetter(1))
		babaovo.reverse()
		return babaovo
	else:
		name = max(babaovo,key= lambda a: babaovo.get(a))
		value = babaovo.get(name)
		return name,value




def rt(status):
	#Get the name of the user that originated the RT.
	return status.split()[A_pos].strip('@:;!*&%$#-=+')
	
	
if __name__ == '__main__':
	
	user = "marcelcaraciolo"
	numberToPlot = 10
	
	babaovos = babaovoByPages(user,True)
	print babaovos
	if type(babaovos) == type([]):
		try:
			from pylab import *
		except:
			print "Error: Pylab not available!"
			exit()

		# make a square figure and axes
		figure(1, figsize=(10,10))
		ax = axes([0.1, 0.1, 0.8, 0.8])

		pie([ item[1] for item in babaovos][0:numberToPlot], labels= [ item[0] for item in babaovos][0:numberToPlot], autopct='%1.1f%%', shadow=True)
		title('BabaOvo user: ' + user , bbox={'facecolor':'0.8', 'pad':5})

		show()
